<?php
/**
 * 数据库连接文件
 * Created by PhpStorm.
 * User:tsingStar
 * Date: 2020/5/13
 * Time: 9:40
 */

function link_db()
{
    $config = include_once __DIR__ . "/../database.php";
    try {
        $db = new PDO($config['type'] . ":host=" . $config['hostname'] . ";dbname=" . $config['database'], $config['username'], $config['password']);
        return $db;
    } catch (PDOException $e) {
        echo $e->getMessage();
        die('2');
    }
}

function find($sql, $db)
{
    $r = $db->query($sql . " limit 1");
    if (!$r) {
        return [];
    }
    $r->setFetchMode(PDO::FETCH_ASSOC);
    return $r->fetch();
}

function select($sql, $db)
{
    $r = $db->query($sql);
    if (!$r) {
        return [];
    }
    $r->setFetchMode(PDO::FETCH_ASSOC);
    $arr = $r->fetchAll();
    return $arr;
}

function insertGetId($table_name, $data, $db)
{
    $insert_keys = '';
    $insert_val = '';
    foreach ($data as $k => $v) {
        $insert_keys .= "$k,";
        $insert_val .= '"'.$v.'",';
    }
    $insert_keys = trim($insert_keys, ',');
    $insert_val = trim($insert_val, ',');
    $res = $db->exec('insert into ' . $table_name . ' (' . $insert_keys . ') values (' . $insert_val . ')');
    if ($res) {
        return $db->lastInsertId();
    } else {
        return 0;
    }
}

/**
 * 批量插入
 * @param $table_name
 * @param $data
 */
function insertAll($table_name, $data, $db){
    foreach ($data as $item){
        insertGetId($table_name, $item, $db);
    }
}

function update($sql, $db)
{
    $r = $db->exec($sql);
    if ($r) {
        return $r;
    } else {
        return 0;
    }
}

function delete($sql, $db){
    $r = $db->exec($sql);
    if ($r) {
        return $r;
    } else {
        return 0;
    }
}


function points_his($db, $uid, $isadd, $nums, $fromid, $info = '')
{
    $data['uid'] = intval($uid);
    $data['isadd'] = $isadd;
    $data['nums'] = $nums;
    $data['fromuid'] = $fromid;
    $data['ctime'] = time();
    $data['info'] = $info;
    return insertGetId('sxs_points', $data, $db);
}

function get_redis()
{
    try {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->select(0);
        return $redis;
    } catch (Exception $e) {
        die("redis服务连接失败");
    }
}

/*本金和天数以及百分比进来，获取一共多少利息，本金和利息分别是多少*/
function countprofit($price,$day,$percent){
    $profit = ($price*$percent/100);
    $profit = round($profit,2);
    $profit_day = ($profit/$day);
    $profit_day = round($profit_day,2);
    $can_have = ($price+$profit);
    return ['profitall'=>$profit,'profitday'=>$profit_day,'profit_and_day'=>$can_have];
}

function excommend($str){
    $str = explode(',',$str);
    $uidary = [];
    foreach($str as $v){
        if(!empty($v) && $v>0){
            $uidary[] = $v;
        }
    }
    return $uidary;
}

class Sms
{
    private static $corpid = 'NJLKJ0006447';
    private static $pwds = 'zh9527@';
    private $settings = [];
    public function __construct()
    {

    }
    /**
     *Date:2020-01-14 18:20:54
     *For: 短信接口查询调用
     */
    static function set_phone($tel, $code = '')
    {
        header("Content-type: text/html; charset=utf-8");
        date_default_timezone_set('PRC');
        $uid = self::$corpid;
        $passwd = self::$pwds;
        //检查短信开关 xuanfeng 2020-02-27
        $config = include __DIR__.'/../extra/setting.php';
        if ($config["smsmy_on"] == 2) {
            $ary = ['status' => '10000', 'tips' => '短信通道已关闭，请联系管理员！'];
            return $ary;
        }
        $message = "尊敬的用户您好，您有新的订单请尽快查看。【全民共享】";
        $msg = rawurlencode(mb_convert_encoding($message, "gb2312", "utf-8"));
        $request_url = "https://mb345.com/ws/BatchSend2.aspx?CorpID=" . $uid . "&Pwd=" . $passwd . "&Mobile=" . $tel;
        $gateway = $request_url . "&Content=" . $msg . "&Cell=&SendTime=";
        $result = file_get_contents($gateway);
        if ($result > 0) {
            $ary = ['status' => '10001', 'tips' => 'success', 'recode' => $result, 'code' => $code];
        } else {
            $ary = ['status' => '10000', 'tips' => '发送失败，错误代码：' . $result];
        }
        return $ary;
    }

    /**
     * 发送订单提醒
     */
    public function send_order_tips($mobile, $db)
    {
        //记录短信记录
        $insertId = insertGetId('sxs_sms_log', [
            "telephone" => $mobile,
            "vcode" => "0000",
            "exp_time" => time() + 1000,
            "type" => 4,
            "create_time" => time()
        ], $db);
        if (!$insertId) {
            return false;
        }
        //尊敬的用户您好，您有新的订单请尽快查看，换短信接口
        $ary = self::set_phone($mobile, 2);
        if ($ary['status'] == '10001') {
            update('update sxs_sms_log set status=1 where id='.$insertId, $db);
            return true;
        } else {
            update('update sxs_sms_log set status=-1, remarks="系统异常"'.$ary['tips'].' where id='.$insertId, $db);
            return false;
        }

    }

}

